package com.intelligent.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.intelligent.dto.PurchaseSupplierQueryDTO;
import com.intelligent.dto.PurchaseSupplierAddDTO;
import com.intelligent.service.PurchaseSupplierService;
import com.intelligent.service.TUserService;
import com.intelligent.utils.Result;
import com.intelligent.vo.PurchaseSupplierVO;
import com.intelligent.pojo.TUser;
import com.intelligent.pojo.PurchaseSupplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/purchase/supplier")
public class PurchaseSupplierController {

    @Autowired
    private PurchaseSupplierService purchaseSupplierService;
    @Autowired
    private TUserService tUserService;

    @PostMapping("/page")
    public Result<IPage<PurchaseSupplierVO>> pageList(@RequestBody PurchaseSupplierQueryDTO query) {
        IPage<PurchaseSupplierVO> page = purchaseSupplierService.pageList(query);
        return Result.success(page);
    }

    @PostMapping("/add")
    public Result<Boolean> addSupplier(@RequestBody PurchaseSupplierAddDTO addDTO) {
        try {
            boolean success = purchaseSupplierService.addSupplier(addDTO);
            return success ? Result.success(true) : Result.error("新增供应商失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("新增供应商失败: " + e.getMessage());
        }
    }

    @PostMapping("/users")
    public Result<List<TUser>> listUsers() {
        List<TUser> list = tUserService.list();
        return Result.success(list);
    }

    /**
     * 获取供应商列表（用于下拉选择）
     * @return 供应商列表
     */
    @GetMapping("/list")
    public Result<List<Map<String, Object>>> getSupplierList() {
        try {
            List<PurchaseSupplier> suppliers = purchaseSupplierService.list();
            
            // 转换为前端需要的格式
            List<Map<String, Object>> result = suppliers.stream()
                .filter(supplier -> supplier.getStatus() == 1) // 只获取启用状态的供应商
                .map(supplier -> {
                    Map<String, Object> supplierMap = new java.util.HashMap<>();
                    supplierMap.put("value", supplier.getId());
                    supplierMap.put("label", supplier.getSupplierName() + " (" + supplier.getSupplierCode() + ")");
                    return supplierMap;
                })
                .collect(java.util.stream.Collectors.toList());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取供应商列表失败：" + e.getMessage());
        }
    }

}
